﻿using CRM.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;

namespace CRM.Extensions
{
    public static class ClaimsPrincipalExtension
    {
        public static bool HasPermission(this IEnumerable<UserClaim> userClaims, Menu menu)
        {
            return userClaims.Any(clm => clm.ClaimType.Equals(menu.Module) && Convert.ToBoolean(menu.PermissionFlag & (Convert.ToInt64(clm.ClaimValue))));
        }
        public static bool HasPermission(this RuleTemplate  tpl, Menu menu)
        {
            return Convert.ToBoolean((long)tpl.GetPropOrFieldValue(menu.Module) & menu.PermissionFlag);
        }
       public static bool HasPermission(this ClaimsPrincipal User, string EnumType, long value)
       {
                //严格模式
                //return User.HasClaim(clm => clm.Type.Equals(EnumType) && (value & Convert.ToInt64(clm.Value))== value);
                //宽松模式 容错 提高兼容性
                return User.HasClaim(clm => clm.Type.Equals(EnumType) && Convert.ToBoolean(value & (Convert.ToInt64(clm.Value))));
        }
        public static bool HasPermission(this ClaimsPrincipal User, Menu m)
        {
            return User.HasPermission(m.Module, m.PermissionFlag);
        }
        public static bool HasPermission<TEnum>(this ClaimsPrincipal User, TEnum @enum)
        {
            return User.HasPermission(nameof(TEnum), Convert.ToInt64(@enum));
        }
        public static bool HasPermission(this ClaimsPrincipal User,string EnumType,Enum value)
        {
            return User.HasPermission(EnumType, Convert.ToInt64(value));
        }
    }
}
